'use strict';
const db = uniCloud.database();
const floorsCollection = db.collection('floors');
const roomsCollection = db.collection('rooms');

exports.main = async (event, context) => {
	const { floor_id, token } = event;
	
	if (!floor_id) {
		return {
			code: 400,
			message: '缺少楼层ID'
		};
	}
	
	if (!token) {
		return {
			code: 401,
			message: '未登录'
		};
	}
	
	try {
		// 开始数据库事务
		const transaction = await db.startTransaction();
		
		try {
			// 1. 获取该楼层下所有房间的信息
			const roomsResult = await roomsCollection.where({
				floor_id: floor_id
			}).get();
			
			// 2. 收集所有需要删除的图片
			const allImages = [];
			roomsResult.data.forEach(room => {
				if (room.images && room.images.length > 0) {
					allImages.push(...room.images);
				}
			});
			
			// 3. 删除云存储中的图片
			if (allImages.length > 0) {
				try {
					await uniCloud.deleteFile({
						fileList: allImages
					});
				} catch (e) {
					console.error('删除云存储图片失败', e);
				}
			}
			
			// 4. 删除该楼层下的所有房间
			await roomsCollection.where({
				floor_id: floor_id
			}).remove();
			
			// 5. 删除楼层
			await floorsCollection.doc(floor_id).remove();
			
			// 提交事务
			await transaction.commit();
			
			return {
				code: 0,
				message: '删除成功'
			};
		} catch (error) {
			// 回滚事务
			await transaction.rollback();
			throw error;
		}
	} catch (error) {
		console.error('删除楼层失败', error);
		return {
			code: 500,
			message: error.message || '删除失败'
		};
	}
}; 